//
//  CZOAuthViewController.swift
//  WeiBoNew
//
//  Created by 秦川 on 16/5/11.
//  Copyright © 2016年 秦川. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
let WeiboAppKey = "4118306637"
let WeiboRedirect_Uri = "http://www.baidu.com"
//code=ffbeb29e9b10536df5855588877869f3
let WeiboAppSecret = "ca1cc0b0d6dd67ae31cf8b673036422c"
class CZOAuthViewController: UIViewController {
    //  MARK:   --懒加载
    //  创建webview
    private lazy var webview: UIWebView = UIWebView()
    override func loadView() {
        webview.delegate = self
        view = webview
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavUI()
        
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        print(url)
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        webview.loadRequest(request)
        
        
        
        
    }
    
    private func setupNavUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
        navigationItem.title = "微博登陆"
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc private func cancelAction(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFillAction(){
        webview.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18500639343'; document.getElementById('passwd').value = 'qin@515'")
        
    }
    // 通过code  获取accesstoken
//    private func requestAccessToken(code: String){
//        CZNetWorkTools.shareTools.requestAccessToken(code) { (response, error) -> () in
//            if error != nil {
//                //                print("数据不是一个正确的json格式")
//                //                print(error)
//                return
//            }
//            guard let dict = response as? [String: AnyObject] else{
//                print("数据不是一个正确的json格式")
//                return
//            }
//            let userAccount = CZUserAcount(dict: dict)
//            print(userAccount)
//            self.requestUserInfo(userAccount)
//            
//            
//        }
        //        let url = "https://api.weibo.com/oauth2/access_token"
        //        let params = [
        //            "client_id" : WeiboAppKey,
        //            "client_secret" :WeiboAppSecret,
        //            "grant_type" : "authorization_code",
        //
        //            "code" :code,
        //            "redirect_uri": WeiboRedirect_Uri
        //        ]
        //        let sessionManager = AFHTTPSessionManager()
        //        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //        sessionManager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
        //            print(response)
        //
        //            guard let dict = response as? [String: AnyObject] else{
        //                print("数据不是一个正确的json格式")
        //                return
        //            }
        //            let userAccount = CZUserAcount(dict: dict)
        //            print(userAccount)
        //            self.requestUserInfo(userAccount)
        //
        //            }) { (_, error) -> Void in
        //                print(error)
        //        }
        //
//    }
//    //  获取用户信息
//    private func requestUserInfo(userAccount: CZUserAcount){
//        
//        CZNetWorkTools.shareTools.requestUserInfo(userAccount) { (response, error) -> () in
//            if error != nil {
//                return
//            }
//            guard let dict = response as? [String: AnyObject] else{
//                print("数据不是一个正确的json格式")
//                return
//            }
//            userAccount.name = dict["name"] as? String
//            userAccount.avatar_large = dict["avatar_large"] as? String
//            userAccount.saveUserAccount()
//            print(userAccount)
//            
//        }
//        
    
        //        let url = "https://api.weibo.com/2/users/show.json"
        //        let params = [
        //            "access_token": userAccount.access_token!,
        //            "uid": "\(userAccount.uid)"
        //        ]
        //        let sessionManager = AFHTTPSessionManager()
        //        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //        sessionManager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
        //            print(response)
        //
        //            guard let dict = response as? [String: AnyObject] else{
        //                print("数据不是一个正确的json格式")
        //                return
        //            }
        //            userAccount.name = dict["name"] as? String
        //            userAccount.avatar_large = dict["avatar_large"] as? String
        //
        //
        //            }) { (_, error) -> Void in
        //                print(error)
        //        }
        //
        //
        //
        
//        
//    }
//    
    
    
    
    
    
    
    
    
    
    
}
//  实现UIWebView代理方法
extension CZOAuthViewController: UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL?.absoluteString)
        //判断地址是否为nil
        guard let url = request.URL else{
            
            return false
            
        }
        //判断地址是否是我们想要的
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri){
            return true
        }
        if let query = url.query where query.hasPrefix("code="){
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            
//            requestAccessToken(code)
          CZUserAccountViewModel.shareUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
            if isSuccess{
//                进入欢迎界面
              print("登陆成功")
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                     
                    //发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                })
                
            }else{
             SVProgressHUD.showErrorWithStatus("登陆失败")
            }
          })
            
        }else{
        dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}








